package com.atguigu.gmall.realtime.dim.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.base.BaseApp;
import com.atguigu.gmall.realtime.common.bean.TableProcessDim;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.atguigu.gmall.realtime.common.util.FlinkSourceUtil;
import com.atguigu.gmall.realtime.common.util.HBaseUtil;
import com.atguigu.gmall.realtime.dim.function.DimSinkFunction;
import com.atguigu.gmall.realtime.dim.function.TableProcessFunction;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

/**
 * @author Felix
 * @date 2024/7/24
 * Dim维度层处理
 * 需要启动的进程
 *      zk、kafka、maxwell、hdfs、HBase、DimApp
 * 代码开发的流程
 *      基本环境准备
 *      检查点设置
 *      从kafka的topic_db主题中读取数据
 *      对读取的数据进行类型转换以及ETL   jsonStr->jsonObj
 *      创建MySqlSource
 *      读取配置表数据封装为流
 *      对读取的数据进行类型转换   jsonStr->实体类对象
 *          op==d : 从before属性中获取配置信息
 *          op!=d : 从after属性中获取配置信息
 *      根据配置信息到hbase中执行建表或者删表
 *          op=c||op=r：建表
 *          op=d：建表
 *          op=u：先删表，再建表
 *      对配置流进行广播---broadcast(广播状态描述器)     K:维度表表名   V:对应配置对象
 *      关联主流业务数据和广播流配置数据---connect
 *      对关联后的数据进行处理---process
 *          class TableProcessFunction extends BroadcastProcessFunction{
 *              open: 将配置信息预加载到程序中，主要解决主流数据先到，广播流数据后到的问题
 *              processElement:处理主流数据
 *                  根据表名到广播状态以及ConfigMap中获取对应的配置信息，如果配置信息不为空，说明是维度
 *                      封装Tuple2(dataJsonObj,配置对象)向下游传递
 *                      在向下游传递数据前，过滤掉不需要传递的字段
 *                      在向下游传递数据前，补充了type
 *              processBroadcastElement:处理广播流数据
 *                  op!=d 将配置信息添加到广播状态或者ConfigMap
 *                  op==d 将配置信息从广播状态或者ConfigMap中删除
 *          }
 *      将维度数据同步到HBase表中
 *          class DimSinkFunction extends RichSinkFunction{
 *              invoke:
 *                      type="delete":从hbase表中删除一条数据
 *                      type!="delete":向hbase表put一条数据
 *
 *          }
 * 执行流程分析(以修改品牌维度为例)
 *      当程序启动的时候，会将配置表中的配置信息加载到ConfigMap以及广播状态中
 *      如果品牌维度表发生了变化
 *      binlog会记录变化
 *      maxwell会从binlog中读取变化数据并封装为json发送给kafka的topic_db主题
 *      flink程序会从kafka主题中读取数据
 *      根据读取的表名到广播状态以及ConfigMap中获取对应的配置信息
 *      如果获取到了，说明是维度，同步到HBase
 *
 */
public class DimApp extends BaseApp {
    public static void main(String[] args) throws Exception {
        new DimApp().start(10002,4,"dim_app_group",Constant.TOPIC_DB);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaStrDS) {
        //TODO 对流中数据进行类型转换并进行简单的ETL    jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = etl(kafkaStrDS);

        //TODO 使用FlinkCDC从配置表中读取配置信息
        SingleOutputStreamOperator<TableProcessDim> tpDS = readTableProcess(env);

        //TODO 在广播配置信息前，根据配置流中的配置在HBase中执行建表或者删除表操作
        tpDS = createHBaseTable(tpDS);

        //TODO 广播配置流---broadcast  关联主流业务数据以及广播流配置信息---connect 对关联后的数据进行处理---process
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS = connect(tpDS, jsonObjDS);

        //TODO 将维度数据同步到HBase对应的表中
        writeToHBase(dimDS);
    }

    private static void writeToHBase(SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS) {
        dimDS.print();
        dimDS.addSink(new DimSinkFunction());
    }

    //关联主流和广播流 并对关联后的数据进行处理
    private static SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> connect(SingleOutputStreamOperator<TableProcessDim> tpDS, SingleOutputStreamOperator<JSONObject> jsonObjDS) {
        MapStateDescriptor<String, TableProcessDim> mapStateDescriptor
                = new MapStateDescriptor<String, TableProcessDim>("mapStateDescriptor", String.class, TableProcessDim.class);
        BroadcastStream<TableProcessDim> broadcastDS = tpDS.broadcast(mapStateDescriptor);

        //关联主流业务数据以及广播流配置信息---connect
        BroadcastConnectedStream<JSONObject, TableProcessDim> connectDS = jsonObjDS.connect(broadcastDS);

        //对关联后的数据进行处理---process
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS = connectDS.process(
                new TableProcessFunction(mapStateDescriptor)
        );
        return dimDS;
    }

    //根据配置流中的配置在HBase中执行建表或者删除表操作
    private static SingleOutputStreamOperator<TableProcessDim> createHBaseTable(SingleOutputStreamOperator<TableProcessDim> tpDS) {
        tpDS = tpDS.map(
                new RichMapFunction<TableProcessDim, TableProcessDim>() {
                    private  Connection hBaseConn;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        hBaseConn = HBaseUtil.getHBaseConnection();
                    }

                    @Override
                    public void close() throws Exception {
                        HBaseUtil.closeHBaseConnection(hBaseConn);
                    }

                    @Override
                    public TableProcessDim map(TableProcessDim tableProcessDim) throws Exception {
                        //获取操作类型
                        String op = tableProcessDim.getOp();

                        //获取操作的hbase表的表名
                        String sinkTable = tableProcessDim.getSinkTable();
                        String[] families = tableProcessDim.getSinkFamily().split(",");
                        if("c".equals(op)||"r".equals(op)){
                            //说明在配置表中新添加了一条数据或者从配置表中读取了一条配置信息，需要在HBase中创建对应的表
                            HBaseUtil.createHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable,families);
                        }else if("d".equals(op)){
                            //说明从配置表中删除了一条配置信息，需要将HBase中对应的表也删除掉
                            HBaseUtil.dropHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable);
                        }else {
                            //说明对配置表中的一条数据进行了修改操作，需要先将HBase表删除掉，在创建新表
                            HBaseUtil.dropHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable);
                            HBaseUtil.createHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable,families);
                        }
                        return tableProcessDim;
                    }
                }
        ).setParallelism(1);
        return tpDS;
    }

    //使用FlinkCDC从配置表中读取配置信息 并对类型进行转换
    private static SingleOutputStreamOperator<TableProcessDim> readTableProcess(StreamExecutionEnvironment env) {
        //创建MySqlSource对象
        MySqlSource<String> mySqlSource = FlinkSourceUtil.getMySqlSource("gmall0221_config", "table_process_dim");
        //读取数据 封装为流
        DataStreamSource<String> mysqlStrDS = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql_source").setParallelism(1);

        //"op":"r":  {"before":null,"after":{"source_table":"base_category3","sink_table":"dim_base_category3","sink_family":"info","sink_columns":"id,name,category2_id","sink_row_key":"id"},"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"gmall0221_config","sequence":null,"table":"table_process_dim","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1721802585234,"transaction":null}
        //"op":"c": {"before":null,"after":{"source_table":"a","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1721802697000,"snapshot":"false","db":"gmall0221_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11381756,"row":0,"thread":8,"query":null},"op":"c","ts_ms":1721802696620,"transaction":null}
        //"op":"u": {"before":{"source_table":"a","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"after":{"source_table":"a","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1721802783000,"snapshot":"false","db":"gmall0221_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11382116,"row":0,"thread":8,"query":null},"op":"u","ts_ms":1721802783558,"transaction":null}
        //"op":"d": {"before":{"source_table":"a","sink_table":"dim_a_b","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"after":null,"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1721802895000,"snapshot":"false","db":"gmall0221_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11382903,"row":0,"thread":8,"query":null},"op":"d","ts_ms":1721802895294,"transaction":null}

        //mysqlStrDS.print();

        //对flinkCDC读取到的数据进行类型转换  jsonStr->实体类对象
        SingleOutputStreamOperator<TableProcessDim> tpDS = mysqlStrDS.map(
                new MapFunction<String, TableProcessDim>() {
                    @Override
                    public TableProcessDim map(String jsonStr) throws Exception {
                        //为了处理方便，先将jsonStr转换为jsonObj
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        //获取操作类型
                        String op = jsonObj.getString("op");

                        TableProcessDim tableProcessDim = null;
                        //判断对配置表做了什么操作
                        if ("d".equals(op)) {
                            //说明从配置表中删除了一条配置，需要从before属性中获取对应的配置信息
                            tableProcessDim = jsonObj.getObject("before", TableProcessDim.class);
                        } else {
                            //说明对配置做了增加、查询、修改操作，需要从after属性中获取对应的配置信息
                            tableProcessDim = jsonObj.getObject("after", TableProcessDim.class);
                        }
                        tableProcessDim.setOp(op);
                        return tableProcessDim;
                    }
                }
        ).setParallelism(1);

        //tpDS.print();
        return tpDS;
    }

    //对流中数据进行类型转换并进行简单的ETL
    private static SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> kafkaStrDS) {
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context ctx, Collector<JSONObject> out) throws Exception {
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        String db = jsonObj.getString("database");
                        String type = jsonObj.getString("type");
                        String data = jsonObj.getString("data");
                        if("gmall0221".equals(db)
                                && ("insert".equals(type)
                                || "update".equals(type)
                                || "delete".equals(type)
                                || "bootstrap-insert".equals(type))
                                && data != null
                                && data.length() > 2
                        ){
                            out.collect(jsonObj);
                        }
                    }
                }
        );
        //jsonObjDS.print();
        return jsonObjDS;
    }
}